package com.xw.bo.ks.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.Base64;

public class AESUtil {

    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String KEY_ALGORITHM = "AES";

    private static final String KEY = "0b3e8fef7c79c7ed31f86d722aedc625";

    private static final String IV = "e5aff18fe6a2cf18";

    public static String encrypt(String plaintext) throws Exception {
        return encrypt(plaintext, KEY, IV);
    }

    public static String encrypt(String plaintext, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String ciphertext) throws Exception {
        return decrypt(ciphertext, KEY, IV);
    }

    public static String decrypt(String ciphertext, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
        return new String(decryptedBytes, "UTF-8");
    }

    public static void main(String[] args) throws Exception {

        int pageNumbers = 11;
        long remainder = 0;
        int pageNumber = pageNumbers + (remainder == 0 ? 0 : 1);
        System.out.println("Encrypted pageNumber:" +pageNumber);

        String plaintext = "{\"code\":\"6026a0b7a93aa4434335c4d3e9a1773d328c5403c65b965a7254315b8b85699b084b258f\",\"state\":\"KWB6RQQ=\",\"request_id\":\"8c03deb2-c829-45b6-aa7b-0de56a687b92\",\"_admin_id\":10000,\"_nickname\":\"SJZS5kyVd8\",\"_company_id\":1}";

//        String key = "0b3e8fef7c79c7ed31f86d722aedc625"; // 256-bit key (32 bytes)
//        String iv = "e5aff18fe6a2cf18"; // 128-bit IV (16 bytes)
//
        String encryptedText = encrypt(plaintext);
        System.out.println("Encrypted Text: ===" );
        System.out.println(encryptedText);
        String encode = URLEncoder.encode(encryptedText, "UTF-8");
//        System.out.println((encode));

        String msg = "jr29U6kAlq/qfeHq350aKrllXr87sFaFMoMnGeQ5q6kTqp1y+4U8oelKeo7liUuM";
//        String msg = encryptedText;
        String decryptedText = decrypt(msg);
        System.out.println("Decrypted Text: " + decryptedText);
    }

}
